﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using XiAnAirport.BUS;
using XiAnAirport.Models;

namespace XiAnAirport.DAL
{
    public class FaultRepairDAL
    {
        public string AddFaultRepairType(FaultRepairType faultRepairType)
        {
            string strSql = string.Format("INSERT INTO fault_repairtype(faultType,faultReason,faultGuidance,maintenancePoint,isDelete)VALUES('{0}','{1}','{2}','{3}',0)", faultRepairType.faultType, faultRepairType.faultReason, faultRepairType.faultGuidance, faultRepairType.maintenancePoint);

            try
            {
                int count = SqlHelper<FaultRepairType>.SqlExecuteRows(strSql);

                if (count > 0)
                {
                    return "success";
                }
                return "fail";
            }
            catch (Exception e)
            {
                return "fail," + e.ToString();
            }
        }

        public string EditFaultRepairType(FaultRepairType faultRepairType)
        {
            string strSql = string.Format("UPDATE fault_repairtype SET faultType='{0}',faultReason='{1}',faultGuidance='{2}',maintenancePoint='{3}' WHERE id={4}", faultRepairType.faultType, faultRepairType.faultReason, faultRepairType.faultGuidance, faultRepairType.maintenancePoint, faultRepairType.id);

            try
            {
                if (SqlHelper<FaultRepairType>.SqlExecute(strSql))
                {
                    return "success";
                }
                else
                {
                    return "fail";
                }
            }
            catch (Exception e)
            {
                return "fail," + e.ToString();
            }
        }

        public string DelFaultRepairType(FaultRepairType faultRepairType)
        {
            string strSql = string.Format("delete FROM fault_repairtype WHERE id={0}", faultRepairType.id);

            try
            {
                int count = SqlHelper<FaultRepairType>.SqlExecuteRows(strSql);
                if (count > 0)
                {
                    return "success";
                }
                else
                {
                    return "fail";
                }
            }
            catch (Exception e)
            {
                return "fail," + e.ToString();
            }
        }

        public FaultRepairType LoadFaultRepairType(int id)
        {
            string strSql = "SELECT * FROM fault_repairtype WHERE id=" + id;
            return SqlHelper<FaultRepairType>.SqlSingleData(strSql);
        }

        public List<FaultRepairType> QueryFaultRepairType(FaultRepairType faultRepairType)
        {
            string strSql = "SELECT * FROM fault_repairtype";
            string sqlwhere = string.Empty;
            List<FaultRepairType> list = new List<FaultRepairType>();
            if (!string.IsNullOrEmpty(faultRepairType.faultType))
            {
                sqlwhere += "faultType like @faultType AND";
            }
            if (sqlwhere.Length > 0)
            {
                strSql += " where " + sqlwhere.Substring(0, sqlwhere.Length - 4);
            }
            if (faultRepairType.Recordhead > -1 && faultRepairType.Recordtail > 0)
            {
                strSql += " LIMIT @Recordhead,@Recordtail";
            }

            using (MySqlConnection connection = DataFactory.GetMysqlConnection())
            {
                MySqlCommand mySqlCommand = new MySqlCommand(strSql, connection);

                // 添加参数
                string likeno = "%" + faultRepairType.faultType + "%";
                mySqlCommand.Parameters.AddWithValue("@faultType", $"%{likeno}%");
                mySqlCommand.Parameters.AddWithValue("@Recordhead", faultRepairType.Recordhead);
                mySqlCommand.Parameters.AddWithValue("@Recordtail", faultRepairType.Recordtail);
                MySqlDataAdapter adapter = new MySqlDataAdapter(mySqlCommand);
                DataSet dataSet = new DataSet();
                adapter.Fill(dataSet);
                DataTable dataTable = dataSet.Tables[0];
                list = ToList<FaultRepairType>(dataTable);
            }

            return list;

        }

        public List<FaultRepairType> QueryAllFaultType()
        {
            string strSql = "SELECT DISTINCT(faultType) FROM fault_repairtype";

            return SqlHelper<FaultRepairType>.SqlList(strSql);

        }

        public int QueryFaultRepairTypeCount(FaultRepairType faultRepairType)
        {
            int count = 0;
            try
            {
                string strSql = "SELECT Count(1) FROM fault_repairtype";
                string sqlwhere = string.Empty;

                if (!string.IsNullOrEmpty(faultRepairType.faultType))
                {
                    sqlwhere += "faultType like @faultType AND";
                }
                if (sqlwhere.Length > 0)
                {
                    strSql += " where " + sqlwhere.Substring(0, sqlwhere.Length - 4);
                }
                using (MySqlConnection connection = DataFactory.GetMysqlConnection())
                {
                    MySqlCommand mySqlCommand = new MySqlCommand(strSql, connection);

                    // 添加参数
                    string likeno = "%" + faultRepairType.faultType + "%";
                    mySqlCommand.Parameters.AddWithValue("@faultType", $"%{likeno}%");
                    MySqlDataAdapter adapter = new MySqlDataAdapter(mySqlCommand);
                    DataSet dataSet = new DataSet();
                    adapter.Fill(dataSet);
                    count = Convert.ToInt32(dataSet.Tables[0].Rows[0][0]);
                }
            }
            catch (Exception ex)
            {

            }
            return count;
        }

        public string CleanUpFaultRepairType()
        {
            string strSql = string.Format("delete FROM fault_repairtype");
            try
            {
                int count = SqlHelper<FaultRepairType>.SqlExecuteRows(strSql);

                if (count > 0)
                {
                    return "success";
                }
                return "fail";
            }
            catch (Exception e)
            {
                return "fail," + e.ToString();
            }
        }


        public string BatchDelFaultRepairType(string ids)
        {
            string strSql = string.Format("delete FROM fault_repairtype WHERE id in ({0})", ids);

            try
            {
                int count = SqlHelper<FaultRepairType>.SqlExecuteRows(strSql);
                if (count > 0)
                {
                    return "success";
                }
                else
                {
                    return "fail";
                }
            }
            catch (Exception e)
            {
                return "fail," + e.ToString();
            }
        }

        public List<FaultRepairType> QueryFaultReasonByType(string type)
        {
            string strSql = "SELECT * FROM fault_repairtype where faultType='" + type + "'";
            return SqlHelper<FaultRepairType>.SqlList(strSql);
        }

        public List<T> ToList<T>(DataTable dt) where T : class, new()
        {
            List<T> list = new List<T>();
            //确认参数有效,若无效则返回Null
            if (dt == null)
                return list;
            else if (dt.Rows.Count == 0)
                return list;
            Dictionary<string, string> dicField = new Dictionary<string, string>();
            Dictionary<string, string> dicProperty = new Dictionary<string, string>();
            Type type = typeof(T);

            //创建字段字典，方便查找字段名
            foreach (var item in type.GetFields())
            {
                dicField.Add(item.Name.ToLower(), item.Name);
            }
            //创建属性字典，方便查找属性名
            foreach (var item in type.GetProperties())
            {
                dicProperty.Add(item.Name.ToLower(), item.Name);
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //创建泛型对象
                T _t = Activator.CreateInstance<T>();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string memberKey = dt.Columns[j].ColumnName.ToLower();

                    //字段赋值
                    if (dicField.ContainsKey(memberKey))
                    {
                        FieldInfo theField = type.GetField(dicField[memberKey]);
                        var dbValue = dt.Rows[i][j];
                        if (dbValue.GetType() == typeof(DBNull))
                            dbValue = null;
                        if (dbValue != null)
                        {
                            Type memberType = theField.FieldType;
                            //dbValue = dbValue.ChangeType(memberType);
                            dbValue = Convert.ChangeType(dbValue, memberType);
                        }
                        theField.SetValue(_t, dbValue);
                    }
                    //属性赋值
                    if (dicProperty.ContainsKey(memberKey))
                    {
                        PropertyInfo theProperty = type.GetProperty(dicProperty[memberKey]);
                        if (!theProperty.CanWrite) continue;
                        var dbValue = dt.Rows[i][j];
                        if (dbValue.GetType() == typeof(DBNull))
                            dbValue = null;
                        if (dbValue != null)
                        {
                            Type memberType = theProperty.PropertyType;
                            if (memberType.IsGenericType && memberType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                            {
                                NullableConverter newNullableConverter = new NullableConverter(memberType);
                                dbValue = newNullableConverter.ConvertFrom(dbValue);
                            }
                            else
                            {
                                dbValue = Convert.ChangeType(dbValue, memberType);
                            }
                        }
                        theProperty.SetValue(_t, dbValue, null);
                    }
                }
                list.Add(_t);
            }
            return list;
        }

    }
}
